<template>
  <div>
    <ul class="list-container">
      <li v-for="item in items" :key="item.id" :class="{ editing: item.isEditing }">
        <!-- 非编辑状态显示文本 -->
        <span v-if="!item.isEditing" class="name-text" @click="handleClick(item)" @dblclick="handleDblClick(item)">
          {{ item.name }}
        </span>

        <!-- 编辑状态显示输入框 -->
        <div v-else class="edit-wrapper">
          <input ref="input" v-model.trim="item.name" @blur="handleBlur(item)" @keyup.enter="handleBlur(item)"
            class="edit-input" :maxlength="10" />
          <div v-if="item.error" class="error-tip">{{ item.error }}</div>
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'demoPage',
  data() {
    return {
      items: [
        { id: 1, name: 'Item 1', isEditing: false, error: '' },
        { id: 2, name: 'Item 2', isEditing: false, error: '' },
        { id: 3, name: 'Long Item', isEditing: false, error: '' }
      ],
      clickTimer: null
    }
  },
  methods: {
    // 处理单击事件（带防冲突）
    handleClick(item) {
      clearTimeout(this.clickTimer)
      this.clickTimer = setTimeout(() => {
        this.executeClick(item)
      }, 200)
    },

    // 实际执行单击操作
    executeClick(item) {
      console.log('Clicked:', item.name)
    },

    // 处理双击事件
    handleDblClick(item) {
      clearTimeout(this.clickTimer) // 清除单击定时器
      this.enterEdit(item)
    },

    // 进入编辑状态
    enterEdit(currentItem) {
      if (currentItem.isEditing) return

      this.items.forEach(item => {
        item.isEditing = item.id === currentItem.id
        item.error = ''
      })

      this.$nextTick(() => {
        // this.$refs.input?.?.focus()
      })
    },

    // 校验逻辑
    validate(item) {
      if (!item.name) return 'Name cannot be empty'
      if (item.name.length > 10) return 'Max length is 10 characters'
      return ''
    },

    // 处理失焦/回车
    handleBlur(item) {
      const error = this.validate(item)
      if (error) {
        item.error = error
        return
      }
      item.isEditing = false
    }
  }
}
</script>

<style scoped>
.list-container {
  list-style: none;
  padding: 0;
  max-width: 400px;
}

li {
  padding: 12px;
  margin: 8px 0;
  border: 1px solid #eee;
  border-radius: 4px;
  transition: all 0.3s;
}

li.editing {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.name-text {
  cursor: text;
  user-select: none;
}

.edit-wrapper {
  position: relative;
}

.edit-input {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  width: 100%;
  outline: none;
}

.error-tip {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
  position: absolute;
  bottom: -22px;
  left: 0;
}
</style>
